<?php

use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\service\wiki\Wiki;
use Doraemon\service\WikiBasic\Schedule;
use Doraemon\tools\BlockType;

/**
 * wiki列表
 */
class WikiListAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;
    const PAGE_SIZE = 20;

    public function main()
    {
        $page = $this->getRequest()->getQuery('page', 1);
        $page = $page > 1 ? $page : 1;
        list($wikIds, $isOver) = $this->getWikiIds($page);
        $data = Wiki::getWikiList($wikIds, $this->uid);
        $list = $this->formatData($data, $isOver);
        $this->setSuccess($list);
    }

    private function formatData($data, $isOver)
    {
        $result = [];
        foreach ($data as $row) {

            $info['type'] = BlockType::TYPE_WIKI;
            $info['wiki'] = $row;

            //$info['statSign'] = '';
            $result[] = $info;
        }
        return ['list' => $result, 'is_over' => $isOver];
    }

    private function getWikiIds($page)
    {
        $wikiIds = [];
        $now = time();
        $brandIds = mBlindBoxActivity::selectByWhere(['activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS, 'prize_stock[>]' => 0, 'start_time[<=]' => $now, 'end_time[>=]' => $now], 'brand_id');
        $brandIds = array_values(array_unique(array_filter($brandIds)));
        $res = Schedule::getWikiListForActivity($page, self::PAGE_SIZE, $brandIds);
        if ($res && $res['rows']) {
            $wikiIds = $res['rows'];
        }
        $isOver = $res ? $res['is_over'] : 1;
        return [$wikiIds, $isOver];
    }
}